'use strict';
import React from "react";
import {
    StyleSheet,
    Text,
    TextInput,
    TextInputComponent,
    TouchableOpacity,
    TouchableOpacityComponent,
    View
} from "react-native";
import Container from "../../component/common/Container";
import NavigationBar from "../../component/navigation/NavigationBar";
import ImageView from "../../component/common/ImageView";
import Button from "../../component/common/Button";
import ListView from "../../component/list/ListView";
import PointGoodsItem from "../../component/item/PointGoodsItem";

class PointShopping extends React.Component {

    constructor(props) {
        super(props);
        this.page = 1;
        this.state = {data: [], headImage: '', category: [], selectedType: '', selectedTypeName: ''};
        this.searchText = '';
    }

    componentDidMount() {
        this.requestImage();
        this.requestList();
        this.requestCatList();
    }

    _onPressDetail = () => {
        // console.log('积分明细');
        RouterHelper.navigate('积分明细', 'PointDetail');
    };

    requestCatList = async () => {
        const result = await Services.post(ServicesApi.GOODS_CATEGORY, {dic_upper: 'goods_category'});
        // console.log('商品目录返回------------>', result);
        if (result.code === StatusCode.SUCCESS_CODE && Array.isArray(result.data)) {
            let catArr = [{dic_code: '全部', dic_name: '全部', select: false}];
            result.data.map((item, i) => {
                const data = {dic_code: item.dic_code, dic_name: item.dic_name, select: false};
                catArr.push(data);
            });
            this.setState({category: catArr})
        }
    };

    requestImage = async () => {
        const result = await Services.post(ServicesApi.SHOPPING_IMAGE, {search_key: 'publicity'});
        // console.log('宣传图片返回--------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            if (Array.isArray(result.data) && result.data.length !== 0) {
                this.setState({headImage: `${ServicesApi.QI_NIU_LINK}${result.data[0].conf_value}`});
                // console.log('宣传图----------->', this.state.headImage);
            }
        }
    };

    requestList = async (searchText) => {
        const limit = 10;
        const data = {
            page: this.page,
            limit,
            goods_category: this.state.selectedType,
            search_key: searchText,
        };
        const result = await Services.post(ServicesApi.SHOPPING_LIST, data);
        // console.log('商品列表返回----------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            if (data.page === 1) {
                this.setState({data: result.data})
            } else {
                if (result.data.length !== 0) {
                    this.setState({data: this.state.data.concat(result.data)});
                }
            }
        } else {
            ToastManager.show(result.dec || 'error');
        }
        this.sectionList && this.sectionList.stopRefresh();
        this.sectionList && this.sectionList.stopEndReached({allLoad: result.data.length < limit})
    };

    _onChangeSearchText = (text) => {
        this.searchText = text;
    };

    //获取lv对象
    _captureRef = (v) => {
        this.sectionList = v;
    };

    _keyExtractor = (item, index) => {
        return `item_${index}`
    };

    _onRefresh = (stopRefresh) => {
        this.page = 1;
        this.requestList()
    };

    _onEndReached = (stopEndReached) => {
        this.page++;
        this.requestList()
    };

    _onPressItem = (index) => {
        const goods_id = this.state.data[index].goods_id;
        // console.log('goods_id-------->', goods_id);
        RouterHelper.navigate('积分商城', 'GoodsDetail', {goods_id});
    };

    _onPressSearch = () => {
        this.page = 1;
        this.requestList(this.searchText);
    };

    _onPressCategory = () => {
        let actionsArr = [];
        this.state.category.map((item, i) => {
            actionsArr.push({
                title: item.dic_name,
                titleStyle: {color: item.select ? '#ffa64f' : '#333333'},
                onPress: () => this.setFilterSelect(item.dic_name, i)
            });
        });

        ActionsManager.show({
            title: '选择筛选类型',
            actions: actionsArr
        });
    };

    setFilterSelect = (name, index) => {
        // console.log('选择了------------>', index);
        let filter = this.state.category;
        filter.map((item, i) => {
            item.select = false;
        });
        if (index !== 0) {
            filter[index].select = true;
            this.setState({
                category: filter,
                selectedType: filter[index].dic_code,
                selectedTypeName: filter[index].dic_name
            });
        } else { //'全部'不选中
            this.setState({category: filter, selectedType: '', selectedTypeName: ''});
        }
        // console.log(this.state.category);
        this.page = 1;
        this.requestList();
    };

    _onPressExchange = (item) => {
        RouterHelper.navigate('积分兑换', 'PointExchange', {item: item})
    };

    // beginDate: null
    // by_sel_count: 0
    // count: 0
    // create_time: 1541986366000
    // endDate: null
    // goods_category: "电脑"
    // goods_desc: "123"
    // goods_desc_imgs: ""
    // goods_id: "0a612dddeb6e4c9fa6c6c24a863faec8"
    // goods_imgs: ",cb911094c3ac4c4cb3acd36246a72c39.jpg"
    // goods_name: "添加测试2"
    // goods_picture: ",4a1e397ba5c14c33bd1dcb08bf7e0f40.jpg"
    // goods_price: 123
    // goods_status: "normal"
    // index: null
    // limit: 10
    // page: 1
    // search_key: null
    // sel_count: null
    // type: null

    renderItem = (info) => {
        const {item, index} = info;
        return (
            <PointGoodsItem
                item={item}
                onPress={() => this._onPressItem(index)}
                onPressSubmit={() => this._onPressExchange(item)}
            />
        );
        const goods_imgs = item.goods_picture ? `${ServicesApi.QI_NIU_LINK}${item.goods_picture}` : '';
        // console.log('goods_imgs----------->',goods_imgs);
        const width = (SCREEN_WIDTH - 8 * 3) / 2;
        const imgHeight = width * 0.720;
        return (
            <TouchableOpacity
                onPress={() => this._onPressItem(index)}
                style={[styles.itemContain, {width}]}>
                <ImageView
                    resizeMode={'cover'}
                    style={{width, height: imgHeight}}
                    source={goods_imgs ? {uri: goods_imgs} : Images.img_shop_default}
                />
                <View style={styles.itemContentView}>
                    <Text style={styles.itemName}>{item.goods_name}</Text>
                    <View style={styles.itemBottomView}>
                        <Text style={styles.itemPoint}>{`${item.goods_price}积分`}</Text>
                        <Button
                            style={styles.itemConvertButton}
                            titleStyle={styles.itemConvertButtonText}
                            title={'兑换'}
                            onPress={() => this._onPressExchange(item)}
                        />
                    </View>
                </View>

            </TouchableOpacity>
        )
    };

    renderHeader = (info) => {
        const width = SCREEN_WIDTH;
        const height = width * 0.314;
        return (
            <View style={styles.headContent}>
                <ImageView
                    style={{width, height}}
                    resizeMode={'stretch'}
                    source={this.state.headImage ? {uri: this.state.headImage} : Images.img_shop_default}
                />
                <View style={styles.searchView}>
                    <View style={styles.typeView}>
                        <Text style={[styles.typeText, {color: this.state.selectedTypeName ? '#ffa64f' : '#9e9e9e'}]}
                              onPress={this._onPressCategory}>{this.state.selectedTypeName ?
                            this.state.selectedTypeName : '分类'}</Text>
                        <ImageView
                            style={styles.typeIcon}
                            source={Images.icon_up_down}
                        />
                    </View>
                    <TextInput
                        style={styles.searchInput}
                        maxLength={20}
                        onChangeText={this._onChangeSearchText}
                    />
                    <Text
                        onPress={this._onPressSearch}
                        style={styles.searchText}>搜索</Text>
                </View>
            </View>
        )
    };

    render() {
        const {params} = this.props.navigation.state;
        const pageTitle = params.pageTitle || '积分商城';
        return (
            <Container>
                <NavigationBar
                    title={pageTitle}
                    renderRightAction={[{
                        title: '积分明细',
                        titleStyle: {color: '#ffa64f'},
                        onPress: this._onPressDetail,
                    }]}
                />

                <ListView
                    data={this.state.data}
                    style={styles.listContent}
                    numColumns={2}
                    ref={this._captureRef}
                    initialRefresh={false}
                    enableLoadMore={true}
                    enableRefresh={true}
                    keyExtractor={this._keyExtractor}
                    ListHeaderComponent={this.renderHeader}
                    // renderSectionHeader={this.renderSectionHeader}
                    renderItem={this.renderItem}
                    onRefresh={this._onRefresh}
                    onEndReached={this._onEndReached}
                />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    headContent: {
        paddingBottom: 15,
        borderBottomWidth: 10,
        borderColor: '#f5f5f5',
    },
    searchView: {
        marginTop: 10,
        marginHorizontal: 8,
        paddingHorizontal: 11,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 30,
        borderWidth: Theme.minPixel,
        borderColor: "#dbdbdb",
        paddingVertical: 10,
    },
    typeView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    typeText: {
        fontSize: FontSize(16),
        color: "#9e9e9e",
    },
    typeIcon: {
        marginLeft: 5,
        width: 6,
        height: 12,
    },
    searchInput: {
        marginHorizontal: 5,
        flex: 1,
        padding: 0,
        color: '#333',
    },
    searchText: {
        fontSize: FontSize(17),
        color: "#ffa64f"
    },
    listContent: {
        marginTop: 13,
        // marginHorizontal: 4,
    },


});

export default PointShopping